<template>
	<view class="page">
		<!-- 顶部导航：与项目其它页面一致 -->
		<image src="/static/dingbu.png" class="mine-navbar-bg" :style="{ height: navbarHeight + 'rpx' }" mode="aspectFill">
		</image>
		<u-navbar title="土壤检测标准" :autoBack="true" leftIconColor="#fff" bgColor="transparent" :titleStyle="{ color: '#fff' }"
			safeAreaInsetTop placeholder>
			<view class="u-nav-slot" slot="right">
				<view class="nav-add-btn" @click="onAdd">添加</view>
			</view>
		</u-navbar>
		<view class="content">
			<!-- 筛选区 -->
			<view class="card filters">
				<view class="row">
					<text class="label">监测年份</text>
					<view class="range">
						<picker mode="date" fields="year" :value="filters.startYear" @change="onStartYearChange">
							<view class="picker-input" :class="{ placeholder: !filters.startYear }">
								{{ filters.startYear || '请选择' }}
							</view>
						</picker>
					</view>
				</view>
				<view class="row">
					<text class="label">监测类别</text>
					<view class="row-main">
						<uni-data-select class="select" v-model="filters.category" :localdata="categoryOptions" clear
							placeholder="全部" />
						<button class="action primary" @click="onSearch">搜索</button>
					</view>
				</view>
				<view class="row">
					<text class="label">级&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;别</text>
					<view class="row-main">
						<uni-data-select class="select" v-model="filters.level" :localdata="levelOptions" placeholder="请选择级别"
							:disabled="true" />
						<button class="action" @click="onReset">重置</button>
					</view>
				</view>
			</view>

			<!-- 列表 -->
			<view class="list">
				<view v-for="(item, idx) in list" :key="idx" class="card item">
					<view class="item-hd">
						<text class="year">{{ item.monitorYear }}</text>
						<text class="level">{{ getLevelName(item.level) }}</text>
					</view>

					<view class="kv">
						<text class="k">监测类别：</text>
						<text class="v">{{ getCategoryName(item.monitorType) }}</text>
					</view>
					<view class="kv">
						<text class="k">录入人员：</text>
						<text class="v">{{ item.inputUserName }}</text>

					</view>
					<view class="kv">
						<text class="k">录入部门：</text>
						<text class="v">{{ item.inputDepartmentName }}</text>
					</view>
					<view class="kv">
						<text class="k">录入时间：</text>
						<text class="v">{{ item.inputTime }}</text>
					</view>
					<view class="w-650 rowsb mt-20">
						<button class="op" size="mini" @click="viewDetail(item)">查看</button>
						<button class="op" size="mini" @click="edit(item)" v-if="item.status == 'draft'">修改</button>
						<button class="op" size="mini" @click="copyItem(item)">复制</button>
						<button class="op danger" size="mini" @click="remove(item)" v-if="item.status == 'draft'">删除</button>
					</view>
				</view>
			</view>
		</view>

	</view>
</template>

<script>
	import {
		getSoilStandardList,
		typeSoil,
		levelSoil,
		deleteSoilStandard,
		getSoilStandardDetailList,
		addSoilStandard
	} from '@/api/soil'
	import navbarMixin from '@/common/navbarMixin'
	export default {
		mixins: [navbarMixin],
		data() {
			return {
				filters: {
					startYear: '',
					category: '',
					level: ''
				},
				categoryOptions: [],
				levelOptions: [],
				list: [],
				form: {
					monitorYear: '',
					category: '',
					fileName: '',
					filePath: ''
				},
			}
		},
		onLoad() {
			this.typeSoil()
			this.levelSoil().then(() => {
				// 级别选项加载完成后获取列表
				this.getList()
			})
		},
		methods: {
			viewDetail(item) {
				const query = `?monitorYear=${item.monitorYear}&monitorType=${item.monitorType}&level=${item.level}&view=true`
				uni.navigateTo({
					url: `/subPkg/trjcbz/addjcbz${query}`
				})
			},
			remove(item) {
				uni.showModal({
					title: '确认删除',
					content: '删除后不可恢复',
					success: (res) => {
						if (res.confirm) {
							this.deleteSoilStandard({
								monitorYear: item.monitorYear,
								monitorType: item.monitorType,
								level: item.level
							})
							uni.showToast({
								title: '已删除',
								icon: 'none'
							})
						}
					}
				})
			},
			// 删除土壤监测标准
			deleteSoilStandard(params) {
				deleteSoilStandard(params).then(res => {
					this.getList()
				})
			},
			// 获取监测级别
			levelSoil() {
				return levelSoil().then(res => {
					this.levelOptions = res.data.map(item => ({
						value: item.dictValue,
						text: item.dictLabel
					}))
					// 获取级别选项后，设置用户级别
					this.filters.level = uni.getStorageSync('userLevel')
				})
			},
			// 获取类别名称
			getCategoryName(value) {
				const option = this.categoryOptions.find(item => item.value === value)
				return option ? option.text : value
			},
			// 获取级别名称
			getLevelName(value) {
				const option = this.levelOptions.find(item => item.value === value)
				return option ? option.text : value
			},
			// 获取监测类型
			typeSoil() {
				typeSoil().then(res => {
					this.categoryOptions = res.data.map(item => ({
						value: item.dictValue,
						text: item.dictLabel
					}))
				})
			},
			// 获取列表
			getList() {
				// 从本地存储获取用户级别
				this.filters.level = uni.getStorageSync('userLevel')
				const params = {
					pageNum: 1,
					pageSize: 10,
					monitorYear: this.filters.startYear,
					monitorType: this.filters.category,
					level: this.filters.level
				}
				getSoilStandardList(params).then(res => {
					this.list = res.rows
				})
			},
			goBack() {
				uni.navigateBack({
					delta: 1
				})
			},
			onAdd() {
				// this.$refs.addPopup && this.$refs.addPopup.open()
				uni.navigateTo({
					url: `/subPkg/trjcbz/addjcbz`
				})
			},
			onStartYearChange(e) {
				this.filters.startYear = (e.detail && e.detail.value) || ''
			},
			onSearch() {
				this.getList()
			},
			onReset() {
				const userLevel = uni.getStorageSync('userLevel')
				this.filters = {
					startYear: '',
					category: '',
					level: userLevel // 重置时保持用户级别
				}
				// 重置后重新获取列表
				this.getList()
			},
			edit(item) {
				const query = `?monitorYear=${item.monitorYear}&monitorType=${item.monitorType || ''}&level=${item.level || ''}`
				uni.navigateTo({
					url: `/subPkg/trjcbz/addjcbz${query}`
				})
			},
			copyItem(item) {
				// 检查是否选择了检测年份和类别
				if (!this.filters.startYear) {
					uni.showToast({
						title: '请先选择检测年份',
						icon: 'none'
					})
					return
				}
				if (!this.filters.category) {
					uni.showToast({
						title: '请先选择检测类别',
						icon: 'none'
					})
					return
				}

				// 先调用查看土壤监测标准详情接口
				const params = {
					monitorYear: item.monitorYear,
					monitorType: item.monitorType,
					level: item.level
				}

				uni.showLoading({
					title: '复制中...'
				})

				getSoilStandardDetailList(params).then(res => {
					uni.hideLoading()
					if (res && res.rows && res.rows.length > 0) {
						// 修改复制数据的年份和类别为上方选择的
						const copyData = res.rows.map(row => ({
							...row,
							monitorYear: this.filters.startYear,
							monitorType: this.filters.category
						}))
						// 将修改后的数据传递给新增接口
						this.addSoilStandard(copyData)
					} else {
						uni.showToast({
							title: '没有可复制的数据',
							icon: 'none'
						})
					}
				}).catch(err => {
					uni.hideLoading()
					uni.showToast({
						title: err.msg,
						icon: 'none'
					})
				})
			},
			// 新增土壤监测标准
			addSoilStandard(data) {
				addSoilStandard(data).then(res => {
					uni.showToast({
						title: '复制成功',
						icon: 'success'
					})
					// 重置表单
					this.onReset()
					// 重新获取列表
					this.getList()
				}).catch(err => {
					console.error('新增失败:', err)
					uni.showToast({
						title: res.msg,
						icon: 'none'
					})
				})
			},

			closeAdd() {
				this.$refs.addPopup && this.$refs.addPopup.close()
			},
			onFormYearChange(e) {
				this.form.monitorYear = (e.detail && e.detail.value) || ''
			},
			chooseFile() {
				uni.chooseMessageFile({
					count: 1,
					type: 'file',
					success: (res) => {
						const f = res.tempFiles && res.tempFiles[0]
						if (!f) return
						const ok = /(\.xlsx|\.xls|\.docx)$/i.test(f.name)
						if (!ok) return uni.showToast({
							title: '仅支持xlsx、xls、docx',
							icon: 'none'
						})
						this.form.fileName = f.name
						this.form.filePath = f.path || ''
					}
				})
			},
			downloadTpl(ext) {
				// 演示：H5 直接打开新窗；APP 交给系统处理
				const name = ext === 'docx' ? '监测标准.docx' : '监测标准.xlsx'
				// 这里可替换为真实模板地址
				const url = 'about:blank'
				// 简化处理
				if (typeof window !== 'undefined' && window.open) {
					try {
						window.open(url, '_blank')
					} catch (e) {}
				} else if (typeof plus !== 'undefined' && plus.runtime) {
					plus.runtime.openURL(url)
				} else {
					uni.showToast({
						title: '下载 ' + name,
						icon: 'none'
					})
				}
			},
			resetForm() {
				this.form = {
					monitorYear: '',
					category: '',
					fileName: '',
					filePath: ''
				}
			},
			saveForm() {
				if (!this.form.monitorYear) return uni.showToast({
					title: '请选择年份',
					icon: 'none'
				})
				if (!this.form.category) return uni.showToast({
					title: '请选择类别',
					icon: 'none'
				})
				if (!this.form.fileName) return uni.showToast({
					title: '请上传文件',
					icon: 'none'
				})
				uni.showToast({
					title: '已保存（示例）',
					icon: 'none'
				})
				this.closeAdd()
			}
		}
	}
</script>

<style lang="scss" scoped>
	.theme-green {
		--brand: #29a74d;
		--brand-weak: rgba(41, 167, 77, 0.12);
		--brand-press: #229246;
	}

	.page {
		background: #f6f7fb;
		min-height: 100vh;
		/* 注入主题变量容器 */
		@extend .theme-green;
	}

	.content {
		padding: 40rpx 32rpx 72rpx;
	}

	/* 卡片通用样式 */
	.card {
		background: #fff;
		border-radius: 18rpx;
		padding: 20rpx;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.03);
		border: 1rpx solid #eef2ef;
	}

	/* 筛选区 */
	.filters {
		margin-bottom: 20rpx;

		.row {
			display: flex;
			align-items: center;
			margin-bottom: 32rpx;

			&:last-child {
				margin-bottom: 0;
			}

			.label {
				color: #2c3e2f;
				font-size: 30rpx;
				margin-right: 10rpx;
			}

			.range {
				flex: 1;
				display: grid;
				grid-template-columns: 1fr auto 1fr;
				/* 左右各占一半，中间“至”自适应 */
				column-gap: 20rpx;
				align-items: center;
			}

			.picker-input {
				width: 100%;
				min-width: 0;
				/* 允许收缩，避免溢出 */
				box-sizing: border-box;
				height: 60rpx;
				line-height: 60rpx;
				background: #f6fbf8;
				border-radius: 10rpx;
				padding: 0 24rpx;
				color: #111;
				font-size: 32rpx;
				border: 1rpx solid rgba(41, 167, 77, 0.25);

				&.placeholder {
					color: #89a08f;
				}
			}

			/* 保证 picker 在网格列中占满宽度 */
			.range>picker {
				width: 100%;
				display: block;
			}

			.row-main {
				flex: 1;
				display: flex;
				align-items: center;
				gap: 0;
				/* 不依赖 gap，兼容性更好 */
			}

			.select {
				flex: 1;
				--height: 68rpx;

				/* 兼容性变量，部分平台不生效 */
				/* 让下拉看起来更像绿色主题 */
				:deep(.uni-data-checklist) {
					background: #f6fbf8;
					border-radius: 10rpx;
				}

				:deep(.uni-select) {
					border: 1rpx solid rgba(41, 167, 77, 0.25);
					background: #f6fbf8;
					height: 88rpx;
					/* 放大选择框高度 */
					border-radius: 14rpx;
				}

				:deep(.uni-select__input) {
					min-height: 88rpx;
					line-height: 88rpx;
					padding-right: 56rpx;
					/* 给右侧图标更多空间 */
				}

				:deep(.uni-select__input-text) {
					font-size: 32rpx;
				}

				/* 放大清除 X 图标与下拉箭头（统一增大）*/
				:deep(.uni-select .uni-icons),
				:deep(.uni-icons.uniui-clear),
				:deep(.uniui-clear) {
					font-size: 38rpx !important;
				}
			}

			.action {
				height: 60rpx;
				line-height: 60rpx;
				padding: 0 20rpx;
				background: var(--brand-weak);
				color: #16723a;
				border-radius: 14rpx;
				font-size: 32rpx;
				min-width: 160rpx;
				/* 按钮不至于太窄，视觉留白更好 */
				margin-left: 32rpx;
				/* 与左侧控件保持明确的外间距 */
				border: 1rpx solid rgba(41, 167, 77, 0.25);

				&.primary {
					background: var(--brand);
					color: #fff;
					border-color: var(--brand);

					&:active {
						background: var(--brand-press);
					}
				}
			}
		}
	}

	/* 列表 */
	.list {
		display: flex;
		flex-direction: column;
		gap: 20rpx;
	}

	.item {
		position: relative;
		padding-right: 220rpx;
		/* 为右侧按钮预留空间 */
		min-height: 220rpx;

		.item-hd {
			display: flex;
			align-items: center;
			gap: 20rpx;
			margin-bottom: 16rpx;

			.year {
				font-size: 36rpx;
				font-weight: 600;
				color: #1b3d2a;
			}

			.level {
				font-size: 32rpx;
				color: #27a24a;
				background: rgba(41, 167, 77, 0.08);
				padding: 6rpx 16rpx;
				border-radius: 8rpx;
			}
		}

		.kv {
			display: flex;
			flex-wrap: wrap;
			align-items: center;
			font-size: 32rpx;
			margin: 14rpx 0;

			.k {
				color: #4f6658;
			}

			.v {
				color: #213e2a;
			}
		}

		.op {
			min-width: 130rpx;
			height: 68rpx;
			line-height: 68rpx;
			border-radius: 36rpx;
			background: #f6fbf8;
			font-size: 30rpx;
			color: #16723a;
			margin-bottom: 10rpx;
			border: 1rpx solid #16723a;

			&:active {
				transform: scale(0.98);
			}

			&.danger {
				background: #fff1f0;
				color: #ff4d4f;
				border-color: #ff4d4f;
			}
		}
	}

	/* 顶部背景与右侧按钮（与全站一致）*/
	.mine-navbar-bg {
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;

		z-index: 2;
	}

	.u-nav-slot {
		display: flex;
		align-items: center;
		padding-right: 24rpx;
	}

	.nav-add-btn {
		color: #fff;
		background: rgba(255, 255, 255, 0.18);
		border: 1rpx solid rgba(255, 255, 255, 0.35);
		padding: 0 20rpx;
		height: 56rpx;
		line-height: 56rpx;
		border-radius: 28rpx;
		font-size: 26rpx;
	}
</style>